<template>
  <page-meta :page-style="'overflow:' + (show ? 'hidden' : 'visible')"></page-meta>
  <view class="view">
    <view :class="['page-mask', show ? 'page-mask-show' : 'page-mask-hidden']"></view>

    <!-- 购物车顶部浮动 -->
    <view class="top-fixed-menu">
      <view class="fixed-content">
        <view class="menu-left">
          <text>购物车</text>
          <text>
            (
            <text>{{ cartList.length }}</text>
            )
          </text>
        </view>
        <view class="menu-right">
          <view class="manager-btn-wrapper">
            <view class="manager-btn" v-if="!showManager" @click="showManager = true">管理</view>
            <view class="exit-manager-btn" v-else>
              <view class="manager-delete-btn" @click="handleDeleteChoose()">删除</view>
              <view class="manager-cancel-btn" @click="showManager = false">取消</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 商品 -->

    <mCartItem
      v-for="item in cartList"
      :goods.sync="item"
      :gmap="isCheckedMapObj"
      :key="item.id"
      @submit="handleEditParam()"
      @select="handleSelect()"
      @param="handleShowParam()"
      @delete="handleSingleDelete()"
    ></mCartItem>

    <!-- 购物车结算栏 -->
    <view class="bottom-fixed-menu">
      <view class="fixed-content">
        <view class="menu-left">
          <radio :checked="selectedAll" @click="handleselectedAll"></radio>
          全选
        </view>
        <view class="menu-right">
          <view class="total">
            <view class="total-top">
              <view class="total-title">合计 :</view>
              <view class="big-price">
                ￥{{ formatPrice(realDiscountTotalPrice).big }}
                <text class="small-price">.{{ formatPrice(realDiscountTotalPrice).small }}</text>
              </view>
            </view>
            <template v-if="discountTotalPrice != 0">
              <view class="total-bottom">
                <!-- 折扣券计算 -->
                已优惠 ￥{{ discountTotalPrice }}
              </view>
            </template>
          </view>
          <view class="submit-btn" @click="handleSubmitGoods()">结算</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import mCartItem from '@/components/mCartItem/index.vue'
import {
  formatPrice,
  calculateAddPrice,
  calculateAveragePrice,
  calculateDiscountPrice,
  calculateSubPrice,
  calculateTotalPrice
} from '../../utils/formatPrice'

export default {
  components: { mCartItem },
  data() {
    return {
      show: false,
      user_id: '',
      selectedAll: false,
      cartList: [],
      showManager: false,
      totalPrice: '0.00',

      // 用来记录已选商品的个数
      isCheckedCount: 0,
      isCheckedMapObj: null,
      allGoodsCouponList: [],
      kindGoodsCouponList: [],
      constValue: {
        Discount: {
          key: 0
        }
      },
      // 总共优惠的金额
      totalDiscountPrice: 0,
      discountCoupon: {},
      formatPrice,
      calculateDiscountPrice,
      calculateSubPrice
    }
  },
  watch: {
    isCheckedCount(n) {
      if (n < this.cartList.length) {
        this.selectedAll = false
      } else {
        this.selectedAll = true
      }
    },
    cartList: {
      handler(n, o) {
        // console.log(n)
        // 获取到数据时，初始化折扣属性
        let { arr: checkedList, totalPrice: totalPrice } = this.resetDiscountPirceByGoods()
        // console.log(checkedList)
        const resObj = this.computedAddCouponPriceByGoods(checkedList)
        // console.log(resObj)
        // 扣除商品指定折扣总金额的实际金额
        const discountPrice = calculateSubPrice(totalPrice, resObj.discountPrice)
        // console.log(totalPrice)
        const { mapObj: mapObj, totalDiscount: total } = this.computedAddCouponPriceByOrder(resObj.list, discountPrice)
        this.isCheckedMapObj = mapObj
        this.totalDiscountPrice = calculateAddPrice(total, resObj.discountPrice)
        this.totalPrice = totalPrice

        this.isCheckedCount = Object.keys(this.isCheckedMapObj).length
      },
      deep: true
    }
  },
  computed: {
    // 需要支付的最后价格
    realDiscountTotalPrice() {
      if (this.totalPrice == '0.00' || this.totalPrice == 0) return 0
      return calculateSubPrice(this.totalPrice, this.totalDiscountPrice).toFixed(2)
    },
    discountTotalPrice() {
      return this.totalDiscountPrice.toFixed(2)
    }
  },
  onLoad() {
    this.user_id = getApp().globalData.userInfo.id
  },
  onShow() {
    this.selectedAll = false
    this.isCheckedCount = 0
    this.getCartData()
  },
  methods: {
    async handleSubmitGoods() {
      var goodsList = []

      for (let i = 0; i < this.cartList.length; i++) {
        const element = this.cartList[i]
        if (element.is_checked) {
          goodsList.push(element.id)
        }
      }

      if (goodsList.length === 0) {
        uni.showToast({
          icon: 'none',
          title: '未选择商品'
        })
        return
      }

      // console.log(goodsList, this.user_id)

      const { data: res } = await uni.request({
        url: this.$domain.data + '/submitOrderByCart',
        header: getApp().globalData.header,
        method: 'POST',
        data: {
          user_id: parseInt(this.user_id),
          cart_id_list: goodsList
        }
      })

      // console.log(res)

      if (res.status != 200) {
        if (res.status === 222) {
          this.$checkStatus(res.status, res.message)
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/address/index'
            })
          }, 500)
          return
        }

        this.$checkStatus(res.status)
        return
      }

      getApp().globalData.orderInfo = res.data

      uni.navigateTo({
        url: '/pages/pay/index'
      })
    },

    async getCartData() {
      // 获取常量
      const { data: consts } = await uni.request({
        url: this.$domain.data + '/const'
      })

      this.constValue = consts.const

      const { data: res } = await uni.request({
        url: this.$domain.data + '/getCartGoodsList/' + this.user_id,
        header: getApp().globalData.header
      })

      if (res.status != 200) {
        this.$checkStatus(res.status)
        return
      }

      this.cartList = res.data.list
      // console.log(res.data)
      this.allGoodsCouponList = []
      this.kindGoodsCouponList = []
      // 筛选优惠券
      for (let i = 0; i < res.data.coupon_list.length; i++) {
        const element = res.data.coupon_list[i]
        if (element.coupon.all_goods) {
          this.allGoodsCouponList.push(element)
        } else {
          this.kindGoodsCouponList.push(element)
        }
      }
    },
    async handleEditParam(e) {
      const editParam = e

      // 修改参数
      for (let i = 0; i < this.cartList.length; i++) {
        if (this.cartList[i].goods_id == editParam.goods_id) {
          // 修改数量

          const { data: res } = await uni.request({
            url: this.$domain.data + '/updateCartGoods',
            header: getApp().globalData.header,
            method: 'POST',
            data: {
              id: this.cartList[i].id,
              count: editParam.count,
              goods_id: this.cartList[i].goods_id,
              goods_param_id: editParam.param.id
            }
          })

          if (res.status != 200) {
            this.$checkStatus(res.status)
            return
          }

          this.cartList[i].count = editParam.count
          this.cartList[i].goods_param_id = editParam.param.id
          this.cartList[i].goods_param = editParam.param
          this.cartList[i].price = res.data.price

          // 将数据上传服务器保存
          uni.showToast({
            icon: 'success',
            title: '修改参数成功'
          })
          return
        }
      }
    },

    // 折扣按先商品后订单计算
    computedAddCouponPriceByGoods(checkedList) {
      // 遍历商品
      var totalDiscount = 0 // 一共优惠的金额
      for (let i = 0; i < checkedList.length; i++) {
        const element = checkedList[i]
        // 获取该商品的最大折扣券
        // 先找到该商品对应的折扣券
        var couponList = []
        for (let j = 0; j < this.kindGoodsCouponList.length; j++) {
          const coupon = this.kindGoodsCouponList[j]
          // console.log(element, coupon)
          if (element.goods_id == coupon.coupon.goods_of_coupon.goods_id) {
            couponList.push(coupon)
          }
        }
        const dobj = this.searchMaxPriceCoupon(couponList, element.price)
        // console.log(dobj)

        // 打折部分的金额
        var discountPrice = 0
        // 判断优惠券种类
        if (dobj.category === this.constValue.Coupon.key) {
          // console.log('优惠券')
          discountPrice = dobj.discount
        }

        if (dobj.category === this.constValue.Discount.key) {
          // console.log('折扣券')
          const subDiscount = (10 - parseInt(parseFloat(dobj.discount) * 10)) / 10
          discountPrice = calculateDiscountPrice(element.price, subDiscount)
        }
        // console.log(discountPrice, dobj)

        // 赋值
        discountPrice = parseFloat(discountPrice.toFixed(5))
        checkedList[i].goodsDiscount = discountPrice
        totalDiscount = calculateAddPrice(totalDiscount, discountPrice)
      }

      return {
        list: checkedList,
        discountPrice: totalDiscount
      }
    },
    computedAddCouponPriceByOrder(checkedList, totalPrice) {
      const dobj = this.searchMaxPriceCoupon(this.allGoodsCouponList, totalPrice)
      let mapObj = {}
      let totalDiscount = 0
      for (let i = 0; i < checkedList.length; i++) {
        const element = checkedList[i]
        let discountPrice = 0
        // 计算最高优惠
        if (dobj.category === this.constValue.Coupon.key) {
          // 按价格比例扣除优惠价格 比例：商品价格（扣除指定商品优惠券后） / 订单总价（扣除指定商品优惠券后）
          const sub = calculateSubPrice(element.price, element.goodsDiscount)
          // 比例
          const bili = calculateAveragePrice(sub, totalPrice)
          discountPrice = bili * dobj.discount
          // console.log(totalDiscount)
          if (totalDiscount === 0) totalDiscount = dobj.discount
        }

        if (dobj.category === this.constValue.Discount.key) {
          const subDiscount = (1000 - parseInt(parseFloat(dobj.discount) * 1000)) / 1000
          // console.log(dobj)
          discountPrice = calculateDiscountPrice(element.price, subDiscount)
          // console.log(discountPrice)
          totalDiscount = calculateAddPrice(discountPrice, totalDiscount)
        }

        checkedList[i].orderDiscount = parseFloat(discountPrice.toFixed(5))

        mapObj[checkedList[i].id] = checkedList[i]
      }

      return {
        mapObj: mapObj,
        totalDiscount: totalDiscount
      }
    },

    searchMaxPriceCoupon(list, totalPrice) {
      // console.log(totalPrice)
      var max = {
        // 折扣金额
        price: 0,
        p_index: 0,
        p_category: 0,
        c_category: 0,
        c_index: 0,
        // 折扣值 <1 如8折是0.8，这里折扣值越大，折扣力度越小，我们需要计算折扣力度最大的
        cop: 1
      }

      // 遍历优惠券
      for (let i = 0; i < list.length; i++) {
        // 判断优惠券是否满足totalprice，再判断是否最大
        let element = list[i]

        if (parseFloat(element.coupon.limit_price) < parseFloat(totalPrice)) {
          // console.log(max.price < element.coupon.discount, element.coupon.discount)
          // 优惠券
          // console.log(parseFloat(element.coupon.discount) < parseFloat(totalPrice))
          if (
            max.price < parseFloat(element.coupon.discount) &&
            parseFloat(element.coupon.discount) < parseFloat(totalPrice) &&
            this.constValue.Coupon.key === element.coupon.category
          ) {
            // console.log('符合要求的', element)
            max.price = parseFloat(element.coupon.discount)
            max.p_index = i
            max.p_category = this.constValue.Coupon.key
          }

          if (max.cop > element.coupon.discount && this.constValue.Discount.key === element.coupon.category) {
            // console.log('符合要求的折扣券', element)
            max.cop = element.coupon.discount
            max.c_index = i
            max.c_category = this.constValue.Discount.key
          }

          // 折扣券
        }
        // console.log(element)
      }

      const discountPrice = max.cop != 0 ? totalPrice * (1 - max.cop) : 0

      if (parseFloat(discountPrice) < parseFloat(max.price)) {
        return {
          discount: max.price,
          index: max.p_index,
          category: max.p_category
        }
      } else {
        return {
          discount: max.cop,
          index: max.c_index,
          category: max.c_category
        }
      }
    },

    resetDiscountPirceByGoods() {
      let arr = []
      let totalPrice = 0
      for (let i = 0; i < this.cartList.length; i++) {
        if (this.cartList[i].is_checked) {
          this.cartList[i].orderDiscount = 0
          this.cartList[i].goodsDiscount = 0
          totalPrice = calculateAddPrice(totalPrice, this.cartList[i].price)
          arr.push(this.cartList[i])
        }
      }
      return {
        arr: arr,
        totalPrice: totalPrice
      }
    },

    handleDeleteChoose() {
      if (this.isCheckedCount === 0) {
        uni.showToast({
          icon: 'none',
          title: '未选择购物车商品'
        })
        return
      }

      uni.showModal({
        title: '提示',
        content: `是否删除已选列表的${this.isCheckedCount}个商品`,
        success: async (e) => {
          var selectedIdList = []
          if (e.confirm) {
            // 寻找已选商品
            this.cartList.forEach((item) => {
              if (item.is_checked) {
                selectedIdList.push(item.id)
              }
            })

            // console.log(selectedIdList)
            // 删除购物车商品
            const { data: res } = await uni.request({
              url: this.$domain.data + '/deleteCartGoodsList',
              header: getApp().globalData.header,
              method: 'POST',
              data: selectedIdList
            })
            // console.log(res)
            if (res.status != 200) {
              this.$checkStatus(res.status)
              return
            }

            uni.showToast({
              icon: 'success',
              title: '删除成功'
            })

            this.isCheckedCount = 0
            // 刷新购物车商品列表
            this.selectedAll = false
            this.getCartData()
          }
        }
      })
    },
    handleSingleDelete(e) {
      uni.showModal({
        title: '提示',
        content: `是否删除该商品`,
        success: async (resp) => {
          if (resp.confirm) {
            // 删除购物车商品

            const { data: res } = await uni.request({
              url: this.$domain.data + '/deleteCartGoods/' + e.id,
              header: getApp().globalData.header,
              method: 'POST'
            })
            if (res.status != 200) {
              this.$checkStatus(res.status)
              return
            }
            uni.showToast({
              icon: 'success',
              title: '删除成功'
            })

            this.isCheckedCount = 0
            // 刷新购物车商品列表
            this.getCartData()
          }
        }
      })
    },

    handleSelect(e) {
      // 寻找目标

      const index = this.cartList.findIndex((element) => e.id === element.id)
      this.cartList[index].is_checked = e.is_checked
    },

    handleShowParam(show) {
      this.show = show
    },

    handleselectedAll() {
      this.selectedAll = !this.selectedAll
      uni.showLoading({
        title: '计算金额中....'
      })

      if (this.selectedAll) {
        this.cartList.forEach((item) => {
          item.is_checked = true
        })
      } else {
        this.cartList.forEach((item) => {
          item.is_checked = false
        })
      }

      uni.hideLoading()
    }
  }
}
</script>

<style lang="scss" scoped>
.view {
  min-height: 100vh;
  padding: 0 $def-padding;
  box-sizing: border-box;
}

.fixed-content {
  position: fixed;
  width: 100%;
  left: 0;

  padding: $def-padding;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 40upx;
  background-color: #fff;
  box-shadow: $def-shadow;
  z-index: 10;
}

.bottom-fixed-menu,
.top-fixed-menu {
  width: 100%;
  position: relative;
}
.top-fixed-menu {
  height: 80upx;
  .fixed-content {
    padding-top: 70upx;
    // #ifndef H5
    top: -60upx;
    // #endif

    // #ifdef H5
    top: 44px;
    //#endif

    left: 0;
    color: $uni-text-color;
    .menu-left {
      > text:nth-child(1) {
        font-weight: 700;
      }

      text:nth-child(2) {
        font-size: 25upx;
        margin-left: 10upx;

        text {
          font-size: 25upx;
          margin: 0 5upx;
        }
      }
    }

    .menu-right {
      font-size: 30upx;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .manager-btn-wrapper {
        width: 140upx;
        height: 100%;
        padding: 10upx;
        display: flex;
        justify-content: center;
        align-items: center;

        .exit-manager-btn {
          display: flex;

          .manager-delete-btn {
            margin-right: 20upx;
            color: #f5552d;
            cursor: pointer;
          }

          .manager-cancel-btn {
            color: #808080;
            cursor: pointer;
          }
        }
      }
    }
  }
}

.bottom-fixed-menu {
  height: 100upx;
  margin-top: 20upx;

  .fixed-content {
    padding-bottom: 80upx;

    // #ifndef H5
    bottom: -75upx;
    // #endif

    // #ifdef H5
    bottom: 49px;
    //#endif

    left: 0;

    .menu-left {
      font-size: 25upx;
      margin-left: $def-padding;
      color: $uni-text-color-placeholder;

      radio {
        transform: $def-radio-size;
      }
    }

    .menu-right {
      display: flex;
      font-size: 35upx;
      align-items: center;

      .total {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        margin-right: 15upx;

        .total-top,
        .total-bottom {
          display: flex;
          align-items: center;
        }

        .total-bottom {
          font-size: 25upx;
          color: #f58e2d;
        }

        .total-title {
          font-size: 25upx;
        }

        .big-price {
          font-size: 40upx;
          font-weight: 900;
        }

        .small-price {
          font-size: $def-small-price;
        }

        .big-price,
        .small-price {
          color: $def-price-color;
        }
      }

      .submit-btn {
        width: 180upx;
        height: 80upx;
        color: #fff;
        display: flex;
        font-size: 35upx;
        font-weight: 900;
        letter-spacing: 5upx;
        border-radius: 40upx;
        justify-content: center;
        align-items: center;
        background: $def-submit-bg;
      }
    }
  }
}
</style>
